package com.ch999.comparedata.hander;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import com.ch999.comparedata.config.ContextHolder;
import com.ch999.comparedata.entity.DataSourceEnum;
import com.ch999.comparedata.entity.SQLUndoLog;
import net.sf.jsqlparser.statement.Statement;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Date;
import java.util.regex.Pattern;

public abstract class AbstractHandler  implements SQLHandler {


    public final  String insertSql = "insert into %s (%s) values(%s)";

    public final  String updateSql = "update %s set %s where id =%s";

    public final String delSql = "DELETE FROM %s where id =  %s";

    public final String mysqlquerySql = "select * from %s where %s";

    public final String sqlServerquerySql = "select * from %s with(nolock) where %s";

    Statement statement;

    DataSource dataSource;

    String dataSourceType;

    public AbstractHandler(Statement statement, DataSource dataSource,String dataSourceType){
        this.statement = statement;
        this.dataSource = dataSource;
        this.dataSourceType = dataSourceType;
    }

  public String getExecuteSql(String dataSourceType){
      if (dataSourceType == DataSourceEnum.SQLSERVER.getValue()){
          return sqlServerquerySql;
      }else {
          return mysqlquerySql;
      }
  }

    public void addUndoLog (SQLUndoLog sqlUndoLog, String restoreSql) throws SQLException {
        Db.use(dataSource).insert(
                Entity.create("undo_log")
                        .set("content", JSONUtil.toJsonPrettyStr(sqlUndoLog))
                        .set("undo_sql", restoreSql)
                        .set("xid", ContextHolder.getXid())
                        .set("log_state", 0)
                        .set("log_created",new Date())
                        .set("sql_type", sqlUndoLog.getSqlCommandType().toString())
                        .set("table_name", sqlUndoLog.getTableName())
        );

    }
}
